package com.common.app.utls.share

import android.app.Activity
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.text.TextUtils
import androidx.fragment.app.FragmentActivity
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.common.app.R
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.getContext
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.yes
import com.common.base.config.AppConfig.WX_FX_GO_SHARE_ID
import com.common.base.utils.AppUtils
import com.common.base.utils.ToastUtils
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXImageObject
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMMin
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.IdentityHashMap





/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/9/3
 * <p>
 * 描述：分享辅助类
 * <p>
 * 修订历史：
 */
object ShareHelper {

    private var mWXApi: IWXAPI? = null
    const val WX_SESSION = 1000//朋友
    const val WX_CIRCLE = 1001//朋友圈
    const val TAG = "ShareUtils"
    const val THUMB_SIZE = 150 //设置分享到朋友圈的缩略图宽高大小
    private const val maxThumbWidth = 200
    private const val maxThumbSize = 32 * 1024

    /**
     * 初始化分享sdk
     */
    fun initShare(wxId: String) {
        //微信初始化
        mWXApi = WXAPIFactory.createWXAPI(getContext(), wxId, true)
        mWXApi?.registerApp(wxId)
    }

    /**
     * 图文分享：微信，QQ，微博
     */
    fun qwShareUrl(
        title: String,
        description: String,
        url: String,
        imageUrl: String = "",
        shareType: Int = 0
    ) {
        val webpage = WXWebpageObject()
        webpage.webpageUrl = url
        val msg = WXMediaMessage(webpage)
        msg.title = title
        msg.description = description
        imageUrl.contains("http").yes {
            dowPic(imageUrl, object : BitmapCallback {
                override fun onBitmapReady(bitmap: Bitmap) {
                    // 处理下载成功的Bitmap
                    msg.thumbData = bmpToByteArray(bitmap, 4 * maxThumbWidth, 4 * maxThumbSize)
                    val req = SendMessageToWX.Req()
                    req.message = msg
                    if (shareType == 0) {
                        req.scene = SendMessageToWX.Req.WXSceneSession//分享到微信
                    } else {
                        req.scene = SendMessageToWX.Req.WXSceneTimeline //分享到微信朋友圈
                    }
                    mWXApi?.sendReq(req)
                }

                override fun onBitmapFailed() {
                    // 处理下载失败
                }
            })
        }.otherwise {
            val bmp = getBitmap(imageUrl)
            msg.thumbData = bmpToByteArray(bmp, 4 * maxThumbWidth, 4 * maxThumbSize)
            bmp.recycle()

            val req = SendMessageToWX.Req()
            req.message = msg
            if (shareType == 0) {
                req.scene = SendMessageToWX.Req.WXSceneSession//分享到微信
            } else {
                req.scene = SendMessageToWX.Req.WXSceneTimeline //分享到微信朋友圈
            }
            mWXApi?.sendReq(req)
        }
    }

    /**
     * 图片分享
     */
    fun qwShareImage(
        imageUrl: String,
        shareType: Int = 0,
    ) {
        //初始化 WXImageObject 和 WXMediaMessage 对象

        imageUrl.contains("http").yes {
            //使用Glide下载图片,保存到本地
            dowPic(imageUrl, object : BitmapCallback {
                override fun onBitmapReady(bitmap: Bitmap) {
                    // 处理下载成功的Bitmap
                    val imgObj = WXImageObject(bitmap)//设置要分享的图片
                    val msg = WXMediaMessage()
                    msg.mediaObject = imgObj
                    msg.thumbData = bmpToByteArray(bitmap, 4 * maxThumbWidth, 4 * maxThumbSize)

                    //构造一个Req
                    val req = SendMessageToWX.Req()
                    req.message = msg
                    if (shareType == WX_SESSION) {
                        req.scene = SendMessageToWX.Req.WXSceneSession//分享到微信
                    } else {
                        req.scene = SendMessageToWX.Req.WXSceneTimeline //分享到微信朋友圈
                    }
                    //调用api接口，发送数据到微信
                    mWXApi?.sendReq(req)

                }

                override fun onBitmapFailed() {
                    // 处理下载失败
                }
            })
        }.otherwise {
            val bmp = getBitmap(imageUrl)
            val imgObj = WXImageObject(bmp)//设置要分享的图片
            val msg = WXMediaMessage()
            msg.mediaObject = imgObj
            msg.thumbData = bmpToByteArray(bmp, 4 * maxThumbWidth, 4 * maxThumbSize)
            bmp.recycle()

            //构造一个Req
            val req = SendMessageToWX.Req()
            req.message = msg
            if (shareType == WX_SESSION) {
                req.scene = SendMessageToWX.Req.WXSceneSession//分享到微信
            } else {
                req.scene = SendMessageToWX.Req.WXSceneTimeline //分享到微信朋友圈
            }
            //调用api接口，发送数据到微信
            mWXApi?.sendReq(req)
        }
    }

    /**
     * 分享小程序卡片
     */
    fun shareWxMicroProgramCard(
        webpageUrl: String, pagePath: String, title: String,
        desc: String?, thumbPath: String, userName: String,
    ) {
        val transaction: String = buildTransaction("webpage")

        //使用Glide下载图片,保存到本地
        dowPic(thumbPath, object : BitmapCallback {
            override fun onBitmapReady(bitmap: Bitmap) {
                // 处理下载成功的Bitmap
                val miniProgramObj = WXMiniProgramObject()
                miniProgramObj.webpageUrl = webpageUrl // 兼容低版本的网页链接
                miniProgramObj.miniprogramType =
                    WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE // 正式版:0，测试版:1，体验版:2
                miniProgramObj.userName = userName // 小程序原始id
                miniProgramObj.path = pagePath //小程序页面路径

                //初始化 WXMediaMessage 对象
                val msg = WXMediaMessage(miniProgramObj)
                msg.title = title // 小程序消息title
                msg.description = desc // 小程序消息desc
                msg.thumbData = bmpToByteArray(bitmap, 4 * maxThumbWidth, 4 * maxThumbSize)

                //构造一个Req
                val req = SendMessageToWX.Req()
                req.message = msg
                req.transaction = transaction
                req.scene = SendMessageToWX.Req.WXSceneSession//分享到微信
                //调用api接口，发送数据到微信
                mWXApi?.sendReq(req)
            }

            override fun onBitmapFailed() {
                // 处理下载失败
            }
        })
    }

    fun dowPic(thumbPath: String, callback: BitmapCallback) {
        Glide.with(getContext())
            .asBitmap() // 指定要获取Bitmap对象
            .load(thumbPath)
            .into(object : CustomTarget<Bitmap>() {
                override fun onLoadFailed(errorDrawable: Drawable?) {
                    super.onLoadFailed(errorDrawable)
                    // 下载失败的处理
                    ToastUtils.showToast("图片下载失败！")
                    callback.onBitmapFailed()
                }

                override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
                    // 在这里获取到下载后的Bitmap对象
                    // resource即为下载后的Bitmap对象
                    callback.onBitmapReady(resource)
                }

                override fun onLoadCleared(placeholder: Drawable?) {
                    // 清除资源的处理
                }
            })
    }

    private fun buildTransaction(type: String?): String {
        return if (type == null) TimeUtils.getTimeDate() ?: "" else type + TimeUtils.getTimeDate()
    }

    private fun getBitmap(imageUrl: String): Bitmap {
        if (TextUtils.isEmpty(imageUrl)) {
            return BitmapFactory.decodeResource(
                getContext().resources,
                R.mipmap.ic_logo_launcher_round
            )
        }
        return BitmapFactory.decodeFile(imageUrl)
    }

    fun bmpToByteArray(origBitmap: Bitmap?, outWidth: Int, maxBytes: Int): ByteArray? {
        return if (origBitmap != null && origBitmap.byteCount > 0) {
            var hwRadio = 1f
            if (origBitmap.height > 0 && origBitmap.width > 0) {
                hwRadio = origBitmap.height * 1f / origBitmap.width
            }
            val scaledBmp =
                Bitmap.createScaledBitmap(origBitmap, outWidth, (outWidth * hwRadio).toInt(), true)
            var options = 100
            val output = ByteArrayOutputStream()
            scaledBmp.compress(Bitmap.CompressFormat.JPEG, options, output)
            while (output.size() > maxBytes && options > 10) {
                output.reset()
                options = options - 10
                scaledBmp.compress(Bitmap.CompressFormat.JPEG, options, output)
            }
            val result = output.toByteArray()
            try {
                output.close()
            } catch (ignored: IOException) {
            }
            result
        } else {
            null
        }
    }

    interface BitmapCallback {
        fun onBitmapReady(bitmap: Bitmap)
        fun onBitmapFailed()
    }
}